package service

import (
	"api_interface/dao"
	"api_interface/entity"
)

/*
收到提问信息
*/
func GetQuestionMessage(uid int, message_type int) (mes *[]entity.MessageInfo, err error) {
	var mesList []entity.MessageInfo
	if err = dao.SqlSession.Where("receiver_id = ? AND message_type = ?", uid, message_type).Find(&mesList).Error; err != nil {
		return nil, err
	}
	mes = &mesList
	return
}

/*
加入信息
*/

func Join_msg() {
	return
}

//存储消息（完成）

func SaveMessages(message *entity.MessageInfo) (err error) {
	var account entity.AccountInfo
	if err = dao.SqlSession.Where("id=?", message.Sender_id).First(&account).Error; err != nil {
		return err
	}
	message.Sender_name = account.Nam

	if message.Message_type == 1 { //点赞提问，此时receiver_id为提问箱qid
		message.Question_id = message.Receiver_id
		var question entity.QuestionInfo
		if err = dao.SqlSession.Where("id=?", message.Receiver_id).First(&question).Error; err != nil {
			return err
		}
		message.Receiver_id = question.QuestionerId
	}

	if message.Message_type == 2 { //点赞评论,此时receiver_id为提问箱cid
		message.Comment_id = message.Receiver_id
		var comment entity.CommentInfo
		if err = dao.SqlSession.Where("id=?", message.Receiver_id).First(&comment).Error; err != nil {
			return err
		}
		message.Receiver_id = comment.Cid
	}

	if message.Message_type == 3 { //提问消息 此时receiver_id为提问箱id
		var box entity.BoxInfo
		if err = dao.SqlSession.Where("id=?", message.Receiver_id).First(&box).Error; err != nil {
			return err
		}
		message.Receiver_id = box.Oid
	}

	if message.Message_type == 4 { //评论消息 此时receiver_id为提问id
		message.Question_id = message.Receiver_id
		var question entity.QuestionInfo
		if err = dao.SqlSession.Where("id=?", message.Receiver_id).First(&question).Error; err != nil {
			return err
		}
		message.Receiver_id = question.QuestionerId
	}

	if message.Message_type == 5 { //回复消息 此时receiver_id为评论id
		message.Comment_id = message.Receiver_id
		var comment entity.CommentInfo
		if err = dao.SqlSession.Where("id=?", message.Receiver_id).First(&comment).Error; err != nil {
			return err
		}
		message.Receiver_id = comment.Cid
	}

	if message.Message_type == 6 { //加入提问箱 此时receiver_id为提问箱id
		var box entity.BoxInfo
		if err = dao.SqlSession.Where("id=?", message.Receiver_id).First(&box).Error; err != nil {
			return err
		}
		message.Receiver_id = box.Oid
	}

	if err = dao.SqlSession.Create(message).Error; err != nil { //SaveMessage
		return err
	}
	return
}

//设置消息为已读（完成）

func SetMessageRead(id int) (err error) {
	var message entity.MessageInfo
	if err = dao.SqlSession.Where("id=?", id).First(&message).Error; err != nil {
		return err
	}
	message.Is_read = true
	if err = dao.SqlSession.Model(&entity.MessageInfo{}).Where("id=?", id).Update(message).Error; err != nil {
		return err
	}
	return
}

//删除某人的已读消息（完成）

func DeleteMessages(id int) (err error) {
	err = dao.SqlSession.Where("receiver_id=? AND is_read=?", id, true).Delete(&entity.MessageInfo{}).Error
	return
}
